<template>
  <!-- 顶部导航 -->
  <HomeNav />
  
  <div class="order-pay-container">    
    <!-- 面包屑导航 -->
    <div class="breadcrumb">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>确认订单</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!-- 订单信息 -->
    <div class="order-content">
      <!-- 收货地址 -->
      <div class="address-section section-card">
        <h3 class="section-title"><i class="el-icon-location"></i>收货地址</h3>
        <div class="address-list" v-if="addresses.length">
          <el-radio-group v-model="selectedAddress">
            <div v-for="addr in addresses" :key="addr.id" class="address-item">
              <el-radio :label="addr.id">
                <div class="address-info">
                  <div class="info-row">
                    <span class="name">{{ addr.name }}</span>
                    <span class="phone">{{ addr.phone }}</span>
                    <span class="tag" v-if="addr.isDefault">默认</span>
                  </div>
                  <div class="address-detail">
                    {{
                      addr.province + addr.city + addr.district + addr.detail
                    }}
                  </div>
                </div>
              </el-radio>
            </div>
          </el-radio-group>
        </div>
        <el-button type="primary" @click="showAddressDialog = true">
          新增收货地址
        </el-button>
      </div>

      <!-- 商品信息 -->
      <div class="product-section section-card">
        <h3 class="section-title"><i class="el-icon-goods"></i>商品信息</h3>
        <div class="product-info">
          <img
            :src="orderInfo.productImage"
            :alt="orderInfo.productName"
            class="product-image"
          />
          <div class="product-detail">
            <h4>{{ orderInfo.productName }}</h4>
            <p class="product-brief">{{ orderInfo.brief }}</p>
            <div class="price-info">
              <span class="current-price">￥{{ orderInfo.seckillPrice }}</span>
              <span class="original-price"
                >￥{{ orderInfo.originalPrice }}</span
              >
            </div>
          </div>
        </div>
      </div>

      <!-- 配送信息 -->
      <div class="delivery-section section-card">
        <h3 class="section-title"><i class="el-icon-truck"></i>配送方式</h3>
        <el-radio-group v-model="deliveryType">
          <el-radio label="express">快递配送</el-radio>
          <el-radio label="self">到店自提</el-radio>
        </el-radio-group>
        <div class="delivery-time" v-if="deliveryType === 'express'">
          <p>预计送达时间：{{ expectedDeliveryTime }}</p>
        </div>
      </div>

      <!-- 发票信息 -->
      <div class="invoice-section section-card">
        <h3 class="section-title"><i class="el-icon-tickets"></i>发票信息</h3>
        <el-radio-group v-model="needInvoice">
          <el-radio :label="false">不开发票</el-radio>
          <el-radio :label="true">开具发票</el-radio>
        </el-radio-group>
      </div>

      <!-- 优惠券信息 -->
      <div class="coupon-section section-card">
        <h3 class="section-title"><i class="el-icon-ticket"></i>优惠券</h3>
        <div class="coupon-list">
          <el-radio-group v-model="selectedCoupon">
            <div v-for="coupon in availableCoupons" :key="coupon.id" 
                 class="coupon-item" :class="{ disabled: coupon.disabled }">
              <el-radio :label="coupon.id" :disabled="coupon.disabled">
                <div class="coupon-info">
                  <div class="coupon-amount">¥{{ coupon.amount }}</div>
                  <div class="coupon-desc">
                    <div class="coupon-title">{{ coupon.title }}</div>
                    <div class="coupon-time">{{ coupon.validTime }}</div>
                  </div>
                </div>
              </el-radio>
            </div>
          </el-radio-group>
        </div>
      </div>

      <!-- 支付方式 -->
      <div class="payment-method-section section-card">
        <h3 class="section-title"><i class="el-icon-wallet"></i>支付方式</h3>
        <el-radio-group v-model="paymentMethod">
          <div class="payment-methods">
            <el-radio label="wxpay" class="payment-method-item">
              <img src="@/assets/imgs/payment/wxpay.jpg" alt="微信支付">
              <span>微信支付</span>
            </el-radio>
            <el-radio label="alipay" class="payment-method-item">
              <img src="@/assets/imgs/payment/alipay.jpg" alt="支付宝">
              <span>支付宝</span>
            </el-radio>
            <el-radio label="unionpay" class="payment-method-item">
              <img src="@/assets/imgs/payment/unionpay.jpg" alt="银联支付">
              <span>银联支付</span>
            </el-radio>
          </div>
        </el-radio-group>
      </div>

      <!-- 订单金额 -->
      <div class="amount-section section-card">
        <h3 class="section-title"><i class="el-icon-money"></i>订单金额</h3>
        <div class="amount-detail">
          <div class="amount-item">
            <span>商品金额：</span>
            <span>￥{{ orderInfo.seckillPrice }}</span>
          </div>
          <div class="amount-item">
            <span>运费：</span>
            <span>￥{{ deliveryFee }}</span>
          </div>
          <div class="amount-item total">
            <span>应付金额：</span>
            <span class="total-price">￥{{ totalAmount }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部支付按钮 -->
    <div class="payment-bar">
      <div class="payment-info">
        <span class="total-label">应付金额：</span>
        <span class="total-amount">￥{{ totalAmount }}</span>
      </div>
      <el-button type="danger" size="large" @click="handlePayment">
        立即支付
      </el-button>
    </div>

    <!-- 新增地址弹窗 -->
    <el-dialog title="新增收货地址" v-model="showAddressDialog" width="500px">
      <el-form :model="newAddress" :rules="addressRules" ref="addressForm">
        <el-form-item prop="name" label="收货人">
          <el-input
            v-model="newAddress.name"
            placeholder="请输入收货人姓名"
          ></el-input>
        </el-form-item>
        <el-form-item prop="phone" label="手机号码">
          <el-input
            v-model="newAddress.phone"
            placeholder="请输入手机号码"
          ></el-input>
        </el-form-item>
        <el-form-item prop="region" label="所在地区">
          <el-cascader
            v-model="newAddress.region"
            :options="regionOptions"
            placeholder="请选择所在地区"
          ></el-cascader>
        </el-form-item>
        <el-form-item prop="detail" label="详细地址">
          <el-input
            type="textarea"
            v-model="newAddress.detail"
            placeholder="请输入详细地址"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="newAddress.isDefault">设为默认地址</el-checkbox>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddressDialog = false">取消</el-button>
        <el-button type="primary" @click="saveAddress">保存</el-button>
      </template>
    </el-dialog>

    <!-- 支付确认弹窗 -->
    <el-dialog v-model="showPayDialog" title="确认支付" width="400px" center>
      <div class="pay-dialog-content">
        <div class="qrcode-wrapper">
          <img :src="payQrCode" alt="支付二维码" class="pay-qrcode">
        </div>
        <div class="pay-amount">¥{{ totalAmount }}</div>
        <div class="pay-tip">请使用{{ paymentMethodText }}扫码完成支付</div>
        <div class="pay-countdown">
          支付倒计时：{{ payCountdown }}秒
        </div>
      </div>
      <template #footer>
        <el-button @click="cancelPayment">取消支付</el-button>
        <el-button type="primary" @click="confirmPayment">已完成支付</el-button>
      </template>
    </el-dialog>
  </div>

  <HomeFooter />
  <div style="height: 80px;">
  <!-- 占位符，避免底部被遮挡 -->
  </div>
</template>

<script setup>
import { ref, computed, onUnmounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import HomeNav from '@/components/layout/HomeNav.vue'
import HomeFooter from '@/components/layout/HomeFooter.vue'

const router = useRouter();

// 订单信息
const orderInfo = ref({
  productName: "示例商品",
  productImage: require("@/assets/imgs/goods/goods01.png"),
  brief: "商品简介",
  seckillPrice: 999,
  originalPrice: 1999,
});

// 收货地址相关
const addresses = ref([
  {
    id: 1,
    name: "张三",
    phone: "13800138000",
    province: "北京市",
    city: "北京市",
    district: "朝阳区",
    detail: "三里屯SOHO",
    isDefault: true,
  },
]);
const selectedAddress = ref(1);
const showAddressDialog = ref(false);

// 配送方式
const deliveryType = ref("express");
const deliveryFee = computed(() => (deliveryType.value === "express" ? 10 : 0));
const expectedDeliveryTime = computed(() => {
  const date = new Date();
  date.setDate(date.getDate() + 3);
  return date.toLocaleDateString();
});

// 发票信息
const needInvoice = ref(false);

// 订单金额计算
const totalAmount = computed(() => {
  return orderInfo.value.seckillPrice + deliveryFee.value;
});

// 新增地址表单
const newAddress = ref({
  name: "",
  phone: "",
  region: [],
  detail: "",
  isDefault: false,
});

// 地址验证规则
const addressRules = {
  name: [{ required: true, message: "请输入收货人姓名", trigger: "blur" }],
  phone: [{ required: true, message: "请输入手机号码", trigger: "blur" }],
  region: [{ required: true, message: "请选择所在地区", trigger: "change" }],
  detail: [{ required: true, message: "请输入详细地址", trigger: "blur" }],
};

// 省市区级联数据
const regionOptions = ref([
  {
    value: '110000',
    label: '北京市',
    children: [
      {
        value: '110100',
        label: '北京市',
        children: [
          { value: '110101', label: '东城区' },
          { value: '110102', label: '西城区' },
          { value: '110105', label: '朝阳区' },
          { value: '110106', label: '丰台区' },
          { value: '110107', label: '石景山区' },
          { value: '110108', label: '海淀区' }
        ]
      }
    ]
  },
  {
    value: '310000',
    label: '上海市',
    children: [
      {
        value: '310100',
        label: '上海市',
        children: [
          { value: '310101', label: '黄浦区' },
          { value: '310104', label: '徐汇区' },
          { value: '310105', label: '长宁区' },
          { value: '310106', label: '静安区' },
          { value: '310107', label: '普陀区' },
          { value: '310109', label: '虹口区' }
        ]
      }
    ]
  },
  {
    value: '440000',
    label: '广东省',
    children: [
      {
        value: '440100',
        label: '广州市',
        children: [
          { value: '440103', label: '荔湾区' },
          { value: '440104', label: '越秀区' },
          { value: '440105', label: '海珠区' },
          { value: '440106', label: '天河区' }
        ]
      },
      {
        value: '440300',
        label: '深圳市',
        children: [
          { value: '440303', label: '罗湖区' },
          { value: '440304', label: '福田区' },
          { value: '440305', label: '南山区' },
          { value: '440306', label: '宝安区' }
        ]
      }
    ]
  }
])

// 保存地址
const saveAddress = () => {
  if (!newAddress.value.name || !newAddress.value.phone || !newAddress.value.region || !newAddress.value.detail) {
    ElMessage.warning('请填写完整的地址信息')
    return
  }

  // 获取省市区名称
  const regionNames = newAddress.value.region.map(code => {
    let name = ''
    let target = regionOptions.value
    for (let i = 0; i < 3; i++) {
      const item = target.find(t => t.value === code)
      if (item) {
        name = item.label
        target = item.children || []
      }
    }
    return name
  })

  // 构造新地址对象
  const address = {
    id: addresses.value.length + 1,
    name: newAddress.value.name,
    phone: newAddress.value.phone,
    province: regionNames[0],
    city: regionNames[1],
    district: regionNames[2],
    detail: newAddress.value.detail,
    isDefault: newAddress.value.isDefault
  }

  // 如果设为默认地址，需要取消其他地址的默认状态
  if (address.isDefault) {
    addresses.value.forEach(addr => addr.isDefault = false)
  }

  // 添加新地址
  addresses.value.push(address)
  
  // 如果是第一个地址，自动选中
  if (addresses.value.length === 1) {
    selectedAddress.value = address.id
  }

  showAddressDialog.value = false
  ElMessage.success('地址添加成功')

  // 重置表单
  newAddress.value = {
    name: '',
    phone: '',
    region: [],
    detail: '',
    isDefault: false
  }
}

// 支付方式
const paymentMethod = ref('wxpay')
const showPayDialog = ref(false)
const payCountdown = ref(300) // 5分钟支付倒计时
let countdownTimer = null

// 优惠券数据
const availableCoupons = ref([
  {
    id: 1,
    amount: 50,
    title: '新人专享券',
    validTime: '2025.6.31前有效',
    disabled: false
  },
  {
    id: 2,
    amount: 100,
    title: '满1000减100',
    validTime: '2025.6.31前有效',
    disabled: true
  }
])
const selectedCoupon = ref(null)

// 支付二维码（模拟）
const payQrCode = computed(() => {
  return require(`@/assets/imgs/payment/qrcode.png`) //${paymentMethod.value}_
})

// 支付方式文本
const paymentMethodText = computed(() => {
  const methodMap = {
    wxpay: '微信',
    alipay: '支付宝',
    unionpay: '银联'
  }
  return methodMap[paymentMethod.value]
})

// 处理支付
const handlePayment = () => {
  if (!selectedAddress.value) {
    ElMessage.warning('请选择收货地址')
    return
  }
  if (!paymentMethod.value) {
    ElMessage.warning('请选择支付方式')
    return
  }
  showPayDialog.value = true
  startPayCountdown()
}

// 开始支付倒计时
const startPayCountdown = () => {
  payCountdown.value = 300
  countdownTimer = setInterval(() => {
    if (payCountdown.value > 0) {
      payCountdown.value--
    } else {
      cancelPayment()
    }
  }, 1000)
}

// 取消支付
const cancelPayment = () => {
  clearInterval(countdownTimer)
  showPayDialog.value = false
  ElMessage.info('已取消支付')
}

// 确认支付
const confirmPayment = () => {
  clearInterval(countdownTimer)
  showPayDialog.value = false
  ElMessage.success('支付成功！')
  router.push('/payment/success')
}

// 组件卸载时清理定时器
onUnmounted(() => {
  clearInterval(countdownTimer)
})
</script>

<style lang="scss" scoped>
.order-pay-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;

  

  .breadcrumb {
    margin-bottom: 20px;
  }

  .section-card {
    background: #fff;
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 20px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);

    .section-title {
      font-size: 18px;
      color: #333;
      margin-bottom: 20px;
      display: flex;
      align-items: center;

      i {
        margin-right: 8px;
        color: #ff4d4f;
      }
    }
  }

  .address-section {
    .address-list {
      margin-bottom: 20px;

      .address-item {
        border: 1px solid #e8e8e8;
        padding: 15px;
        margin-bottom: 10px;
        border-radius: 4px;

        &:hover {
          border-color: #ff4d4f;
        }

        .address-info {
          margin-left: 25px;

          .info-row {
            margin-bottom: 5px;

            .name {
              font-weight: bold;
              margin-right: 20px;
            }

            .phone {
              color: #666;
            }

            .tag {
              background: #ff4d4f;
              color: #fff;
              padding: 2px 6px;
              border-radius: 2px;
              font-size: 12px;
              margin-left: 10px;
            }
          }

          .address-detail {
            color: #666;
          }
        }
      }
    }
  }

  .product-section {
    .product-info {
      display: flex;
      gap: 20px;

      .product-image {
        width: 100px;
        height: 100px;
        object-fit: cover;
        border-radius: 4px;
      }

      .product-detail {
        flex: 1;

        h4 {
          margin: 0 0 10px;
        }

        .product-brief {
          color: #666;
          margin-bottom: 10px;
        }

        .price-info {
          .current-price {
            color: #ff4d4f;
            font-size: 20px;
            font-weight: bold;
            margin-right: 10px;
          }

          .original-price {
            color: #999;
            text-decoration: line-through;
          }
        }
      }
    }
  }

  .amount-section {
    .amount-detail {
      .amount-item {
        display: flex;
        justify-content: space-between;
        margin-bottom: 10px;

        &.total {
          border-top: 1px solid #f0f0f0;
          padding-top: 10px;
          margin-top: 10px;

          .total-price {
            color: #ff4d4f;
            font-size: 20px;
            font-weight: bold;
          }
        }
      }
    }
  }

  .payment-bar {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background: #fff;
    padding: 20px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);

    .payment-info {
      margin-right: 20px;

      .total-label {
        font-size: 16px;
      }

      .total-amount {
        color: #ff4d4f;
        font-size: 24px;
        font-weight: bold;
      }
    }
  }

  .coupon-section {
    .coupon-list {
      display: flex;
      gap: 20px;
      
      .coupon-item {
        border: 1px solid #e8e8e8;
        border-radius: 4px;
        padding: 15px;
        cursor: pointer;
        transition: all 0.3s;
        
        &:hover:not(.disabled) {
          border-color: #ff4d4f;
        }
        
        &.disabled {
          opacity: 0.5;
          cursor: not-allowed;
        }

        .coupon-info {
          display: flex;
          align-items: center;
          gap: 15px;
          margin-left: 25px;

          .coupon-amount {
            font-size: 24px;
            color: #ff4d4f;
            font-weight: bold;
          }

          .coupon-desc {
            .coupon-title {
              font-size: 14px;
              margin-bottom: 5px;
            }
            
            .coupon-time {
              font-size: 12px;
              color: #999;
            }
          }
        }
      }
    }
  }

  .payment-method-section {
    .payment-methods {
      display: flex;
      gap: 30px;

      .payment-method-item {
        display: flex;
        align-items: center;
        gap: 10px;
        padding: 15px;
        border: 1px solid #e8e8e8;
        border-radius: 4px;
        transition: all 0.3s;

        img {
          width: 30px;
          height: 30px;
        }

        &:hover {
          border-color: #ff4d4f;
        }
      }
    }
  }

  .pay-dialog-content {
    text-align: center;
    padding: 20px;

    .qrcode-wrapper {
      margin: 20px 0;
      
      .pay-qrcode {
        width: 200px;
        height: 200px;
      }
    }

    .pay-amount {
      font-size: 24px;
      color: #ff4d4f;
      font-weight: bold;
      margin-bottom: 10px;
    }

    .pay-tip {
      color: #666;
      margin-bottom: 15px;
    }

    .pay-countdown {
      font-size: 14px;
      color: #999;
    }
  }
}
</style>
